package cn.doitedu.rtmk.mgmt.controller;

import cn.doitedu.rtmk.mgmt.service.DynamicTagHistValueService;
import cn.doitedu.rtmk.mgmt.service.RuleInstanceService;
import cn.doitedu.rtmk.mgmt.service.StaticCrowdSelectionService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.roaringbitmap.RoaringBitmap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.function.IntFunction;


@RestController
public class RulePublishController {

    @Autowired
    StaticCrowdSelectionService staticCrowdSelectionService;

    @Autowired
    DynamicTagHistValueService dynamicTagHistValueService;

    @Autowired
    RuleInstanceService ruleInstanceService;




    @RequestMapping("/rule/publish")
    public String publishRule(@RequestBody String paramJsonStr) throws IOException, SQLException {

        JSONObject paramJsonObject = JSON.parseObject(paramJsonStr);

        /**
         * 1. 根据规则实例 参数中的  静态画像标签条件去  圈选人群
         */
        List<Integer> crowedIds = staticCrowdSelectionService.crowdSelect(paramJsonObject);

        // 将 service 查询到的人群id，转成bitmap
        RoaringBitmap crowedBitmap = RoaringBitmap.bitmapOf();
        for (Integer crowedId : crowedIds) {
            crowedBitmap.add(crowedId);
        }


        /**
         * 2. 查询动态画像条件的历史值 并 发布到 redis
         */
        dynamicTagHistValueService.queryDynamicTagHistValue(paramJsonObject,crowedBitmap);


        /**
         * 3. 组装规则实例的资源： 人群bitmap，规则实例的json参数，规则实例的groovy运算机代码
         */
        ruleInstanceService.createRuleInstance(crowedBitmap,paramJsonObject);


        return "success";
    }

}
